package com.mk.controller.user;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.mk.constant.RedisCacheConstant;
import com.mk.entity.Article;
import com.mk.entity.Info;
import com.mk.result.Result;
import com.mk.service.IInformationService;
import com.mk.utils.RedisUtil;
import com.mk.vo.ArticleVO;
import com.mk.vo.InfoVO;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;

/**
 * 资讯中心相关业务
 */
@RestController("userInformationController")
@RequestMapping("/user/info")
@RequiredArgsConstructor
public class InformationController {

    private final IInformationService informationService;
    private final RedisUtil redisUtil;

    /**
     * 获取所有资讯
     * @return
     */
    @CrossOrigin
    @GetMapping("/list")
    public Result<List<InfoVO>> getAll() {
        List<Info> list = informationService.list(new LambdaQueryWrapper<Info>()
                .orderByDesc(Info::getCreateTime));
        return Result.success(BeanUtil.copyToList(list, InfoVO.class));
    }

    /**
     * 根据id获取一条资讯
     * @param infoId
     * @return
     */
    @CrossOrigin
    @GetMapping("/get/{infoId}")
    public Result<InfoVO> getById(@PathVariable Long infoId) {
        Map<Object, Object> map = redisUtil.getHashEntries(RedisCacheConstant.INFORMATION_KEY + infoId);
        if (!map.isEmpty()) {
            String title = map.get(Info.TITLE).toString();
            String text = map.get(Info.TEXT).toString();
            String image = map.get(Info.IMAGE).toString();
            LocalDateTime createTime = LocalDateTime.parse(map.get(Info.CREATE_TIME).toString());
            LocalDateTime updateTime = LocalDateTime.parse(map.get(Info.UPDATE_TIME).toString());

            return Result.success(BeanUtil.copyProperties(
                    Info.builder()
                            .title(title)
                            .text(text)
                            .image(image)
                            .createTime(createTime)
                            .updateTime(updateTime)
                            .build(), InfoVO.class));
        } else {
            return Result.success(BeanUtil.copyProperties(informationService.getById(infoId), InfoVO.class));
        }
    }
}
